package userrouter

import (
	"context"
	"fmt"
	mongodb "golang_note/day08_http/gin/mongo"

	"net/http"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"

	"github.com/gin-gonic/gin"
)

//User ...
type User struct {
	Phonenumber string `json:"phonenumber" form:"phonenumber"`
	Password    string `json:"password" form:"password"`
}

var conn *mongo.Collection

func init() {
	conn = mongodb.Get().Collection("user")
}

//UserRegister ...
func UserRegister(c *gin.Context) {
	var users User
	err := c.ShouldBind(&users)
	if err != nil {
		fmt.Println(err)
	}
	if users.Phonenumber == "" || users.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"status": 1,
			"msg":    "账号或密码为空",
		})
		return
	}
	filter := bson.D{{
		"phonenumber",
		bson.D{{
			"$in",
			bson.A{users.Phonenumber},
		}},
	}}
	var result User
	err = conn.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		insertresult, err := conn.InsertOne(context.TODO(), users)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "1",
				"msg":    "注册失败",
			})
			return
		}
		if insertresult.InsertedID != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "0",
				"msg":    "注册成功",
			})
		}
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status": "1",
			"msg":    "账号已经存在",
		})
	}

}

//UserChangePassword ...
func UserChangePassword(c *gin.Context) {
	var user User
	if err := c.ShouldBind(&user); err == nil && user.Phonenumber != "" && user.Phonenumber != "" {
		filter := bson.D{{
			"phonenumber", user.Phonenumber,
		}}
		update := bson.D{{
			"$set", bson.M{"password": user.Password},
		}}
		fmt.Println(user)
		if updateresult, err := conn.UpdateOne(context.TODO(), filter, update); err == nil && updateresult.ModifiedCount > 0 {
			c.JSON(http.StatusOK, gin.H{
				"status": "0",
				"msg":    "密码修改成功",
			})
		} else {

			c.JSON(http.StatusOK, gin.H{
				"status": "1",
				"msg":    "密码修改失败",
			})
		}

	}
}
